#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#define  ServerPort    4000//服务器端口号
#pragma comment( lib, "ws2_32.lib" ) 
void open(char xs[],int file)//读取文件
{
	FILE *fp;
	if(file==1)
	{
	   if((fp=fopen("1.txt","r"))==NULL)
	   {
			printf("Failure to open file!\n");
			exit(0);
		}
		fread(xs,sizeof(char),100,fp);
		fclose(fp);
	}
	else if(file==2)
	{
	   if((fp=fopen("2.txt","r"))==NULL)
	   {
			printf("Failure to open file!\n");
			exit(0);
		}
		fread(xs,sizeof(char),100,fp);
		fclose(fp);
	}
	else if(file==3)
	{
	   if((fp=fopen("3.txt","r"))==NULL)
	   {
			printf("Failure to open file!\n");
			exit(0);
		}
		fread(xs,sizeof(char),100,fp);
		fclose(fp);
	}
	else 
		printf("选择错误。");
}
int main(int argc, char* argv[])
{

    WSADATA    wsaData;  //WSAData数据结构
    SOCKET     ServerSocket,NewSocket;
    struct sockaddr_in  ServerAddr,ClientAddr;  //地址结构
    int ClientAddrLen;
    char ReceiveBuffer[1024];//接收的数据缓冲区
    int ReceiveLen;   //接收数据
    WSAStartup(MAKEWORD(1, 1), &wsaData);
	printf("你好！我是服务器。\n");

    ServerSocket = socket(AF_INET, SOCK_STREAM, 0);//创建一个套接字用于监听客户端
   
    ServerAddr.sin_family = AF_INET;//填充服务器地址信息
    ServerAddr.sin_port = htons(ServerPort);//设置服务器端口号
    ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);//设置地址

    bind(ServerSocket, (struct sockaddr *) &ServerAddr, sizeof(struct sockaddr));//绑定套接字
    listen(ServerSocket, 5);//监听套接字
   
    ClientAddrLen = sizeof(struct sockaddr);
    int SendLength;//发送
    NewSocket = accept(ServerSocket, (struct sockaddr *) &ClientAddr, &ClientAddrLen);
    if ((ReceiveLen = recv(NewSocket, ReceiveBuffer, 1024, 0)) < 0)//接收数据
    {
                printf("recv failed with error %d\n", WSAGetLastError());
                return ;
    }
    else
    {	
				printf("连接成功\n");
             ReceiveBuffer[1024] = '\0';
             printf("接收到客户端数据:%s\n", ReceiveBuffer);
	}
	char SendBuffer[1024];
	int file;
	
	printf("请输入需要发送的文件：1.txt\n");
	scanf("%d",&file);
   open(SendBuffer,file);
   SendLength = send(NewSocket, SendBuffer, strlen(SendBuffer)+1, 0);//发送数据
   if (SendLength < 0)
   {
          printf("send failed with error %d\n", WSAGetLastError());
          return ;
    }
   else
   {
          printf("成功发送数据\n");
    }
    
   closesocket(NewSocket);
	closesocket(ServerSocket);
	WSACleanup();
}/*
int main(){
	FILE *fp;
	if((fp=fopen("1.txt","w"))==NULL)
	{
		printf("Failure to open file!\n");
		exit(0);
	}

	char xs[100];
	gets(xs);
//	for(int i=0;!feof(fp);i++)
	//{
		fwrite(xs,sizeof(char),100,fp);
	//}
//	printf("%s",xs);
	fclose(fp);
}*/
